<template>
  <div class="login_box">
    <!-- 不推荐使用嵌套布局，避免后面事件冒泡 -->
    <div class="mask" @click="changshow(false)"></div>
    <div class="login">
      <div class="close" @click="changshow(false)">
        <img src="../assets/img/close.png" alt="" />
      </div>
      <section>
        <div class="nav">
          <a
            href="###"
            :class="{ cur: wechatshow }"
            @click="changtwechatshow(true)"
            >手机号登陆</a
          >
          |
          <a href="###" :class="{ cur: !wechatshow }" @click="weChatBtn"
            >微信登陆</a
          >
        </div>
        <div class="content">
          <!-- 手机号登陆 -->
          <div class="phone" v-show="wechatshow">
            <div class="row">
              <input
                type="text"
                placeholder="请输入手机号"
                v-model="phoneNum"
              />
            </div>
            <div class="row">
              <!-- 滑块组件 -->
              <slide-verify
                :l="44"
                :r="10"
                :w="375"
                :h="133"
                @success="onSuccess"
                @fail="onFail"
                @refresh="onRefresh"
                :style="{ width: '100%' }"
                class="slide-box"
                ref="slideBlock"
                :slider-text="msg"
                :imgs="arr"
                :accuracy="accuracy"
              ></slide-verify>
            </div>
            <div class="row">
              <input
                type="text"
                placeholder="请输入短信验证码"
                v-model="code"
              />
              <!-- <button class="codebtn" @click="codebtn">
                {{ isShow ? count : "获取验证码" }}
              </button> -->
              <!-- 上面的方式，连续点击的时候会触发多个定时器 -->
              <button class="codebtn" @click="codebtn" v-show="!isShow">
                获取验证码
              </button>
              <button class="codebtn" v-show="isShow">
                {{ count }}
              </button>
            </div>
            <div class="row">
              <button class="loginbtn" @click="login">登陆</button>
            </div>
          </div>
          <!-- 微信登陆 -->
          <div class="wechat" v-show="!wechatshow" id="weChat"></div>
        </div>
      </section>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions, mapState } from "vuex";
import { sendSMSApi, phoneReginApi, bandingApi } from "../request/api";
import { checkphone } from "../utils/index";

export default {
  data() {
    return {
      show: true,
      msg: "向右滑动",
      // 滑块拼图图片
      arr: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
      ],
      // 误差值
      accuracy: 10,
      // 手机号
      phoneNum: "",
      // 倒计时
      count: 5,
      // 是否显示倒计时
      isShow: false,
      // 验证码
      code: "",
    };
  },
  computed: {
    ...mapState({
      wechatshow: (state) => state.showWechat.wechatshow,
    }),
  },
  methods: {
    ...mapMutations({
      changshow: "loginshow/changshow",
      changisLoginshow: "loginstate/changisLoginshow",
      changtoastshow: "showToast/changtoastshow",
      changshowcontent: "showToast/changshowcontent",
      changtwechatshow: "showWechat/changtwechatshow",
    }),
    ...mapActions({
      asyncChangtoastshow: "showToast/asyncChangtoastshow",
      asyncchanguserInfo: "userInfo/asyncchanguserInfo",
    }),

    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    // 倒计时
    daojishi() {
      // 设置倒计时
      this.isShow = true;
      let timer = setInterval(() => {
        this.count--;
        if (this.count <= 0) {
          this.count = 5;
          clearInterval(timer);
          this.isShow = false;
        }
      }, 1000);
    },

    // 验证条件(手机号+滑块)
    yanzhen() {
      // 验证手机号
      if (!checkphone(this.phoneNum.trim())) {
        // alert("请输入正确的手机号");
        // this.changtoastshow({
        //   show: true,
        //   msg: "请输入正确的手机号",
        //   type: "success",
        // });
        // setTimeout(() => {
        //   this.changtoastshow({
        //     show: false,
        //   });
        // }, 2000);
        // return;
        // 把定时器抽离到vuex中的写法
        this.asyncChangtoastshow({
          show: true,
          msg: "请输入正确的手机号",
          type: "warning",
        });
        return;
      }
      // 验证滑块
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        alert("请滑动滑块验证");
        return;
      }
      return true;
    },

    // 获取验证码
    async codebtn() {
      // 验证条件
      let flag = this.yanzhen();
      if (!flag) return;

      // 发送请求
      let res = await sendSMSApi({ phone: this.phoneNum });
      // res已受拦截器处理
      if (!res) return;
      alert("发送成功");
      this.daojishi();
      console.log(123);
    },

    // 登陆
    async login() {
      //1. 手机号不正确提示
      //2. 滑块不正确提示
      if (!this.yanzhen()) return;
      if (this.code.trim() == "") {
        alert("请输入短信验证码");
        return;
      }
      // 1.判断是否存在uuid，如果存在就发送绑定请求，不存在就普通登陆
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await bandingApi({
          verifyCode: this.code,
          phone: this.phoneNum,
          uuid,
        });
        console.log("有uuid");
      } else {
        res = await phoneReginApi({
          verifyCode: this.code,
          phone: this.phoneNum,
        });
        console.log("没有uuid");
      }

      if (!res) return;
      // console.log(res);
      // 1.提示框
      alert("登陆成功");
      // 2.存token
      localStorage.setItem("token", res["x-auth-token"]);
      // 3.关闭登陆框
      this.changshow(false);
      // 4.切换tobar栏
      this.changisLoginshow(true);

      // 手机绑定微信成功后，清除code、uuid
      uuid && this.$router.push(this.$route.path);
      localStorage.removeItem("uuid");

      // 获取用户信息
      this.asyncchanguserInfo();
    },

    weChatBtn() {
      // 显示微信登陆框
      this.changtwechatshow(false);
      // 微信登录第一步：申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weChat",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICBkaXNwbGF5OiBub25lOw0KfQ0KDQovKiAuaW1wb3dlckJveCAud3JwX2NvZGUgew0KICB0ZXh0LWFsaWduOiBjZW50ZXI7DQp9ICov",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.login_box {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;

  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }

  .login {
    width: 555px;
    height: 423px;
    position: absolute;
    inset: 0;
    margin: auto;
    background-image: url("../assets/img/login-box-bg.png");

    .close {
      cursor: pointer;
      position: absolute;
      top: 16px;
      right: 66px;
      width: 22px;
      height: 22px;
    }

    section {
      width: 100%;
      height: 100%;
      text-align: center;
      .nav {
        margin-top: 30px;

        a {
          margin: 0 10px;
          color: gray;
          text-decoration: none;
          &.cur {
            color: black;
            font-weight: 700;
          }
        }
      }

      .content {
        width: 68%;
        height: 68%;
        margin: 20px auto;

        .phone {
          width: 100%;
          height: 100%;
          padding-top: 10px;

          .row {
            display: flex;
            margin-bottom: 20px;

            input {
              height: 50px;
              flex: 1;
              outline: none;
              text-indent: 1em;
            }

            .codebtn {
              background-color: rgb(10, 50, 142);
              color: white;
              border: none;
              cursor: pointer;
              width: 79px;
            }

            .loginbtn {
              height: 50px;
              background-color: rgb(10, 50, 142);
              color: white;
              border: none;
              flex: 1;
              font-size: 18px;
              letter-spacing: 50px;
              text-indent: 50px;
              cursor: pointer;
            }
          }
        }

        // .wechat {
        //   width: 60px;
        //   height: 60%;
        // }
      }
    }
  }
}

// 修改子组件中的样式
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>